<template>
  <div class="app-container">
    <el-row>
      <el-col :span="10" class="card-box">
        <el-card>
          <template #header><Monitor style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">基本信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table style="width: 100%;">
              <thead>
              <tr>
                <th class="el-table__cell is-leaf"><div class="cell">属性</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">值</div></th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">订单编号</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 4.5px;margin-bottom: 4.5px"
                  >{{orderInfo.orderNo}}</div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">下单时间</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 4.5px;margin-bottom: 4.5px"
                  >{{orderInfo.orderTime}}</div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">勾选货品</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 4.5px;margin-bottom: 4.5px"
                  >{{productsNum}} 种</div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="14" class="card-box">
        <el-card>
          <template #header><Setting style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">配置信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table style="width: 100%;">
              <thead>
              <tr>
                <th class="el-table__cell is-leaf" style="width: 15%"><div class="cell">属性</div></th>
                <th class="el-table__cell is-leaf" style="width: 30%"><div class="cell">值</div></th>
                <th class="el-table__cell is-leaf" style="width: 20%"><div class="cell">属性</div></th>
                <th class="el-table__cell is-leaf"><div class="cell">值</div></th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">*供货商</div></td>
                <td class="el-table__cell is-leaf">
                  <el-select style="width: 54%;" v-model="orderInfo.companyName" @change="handleSupplierChange">
                    <el-option
                        v-for="item in suppliers"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                  </el-select>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">预期到货时间</div></td>
                <td class="el-table__cell is-leaf">
                  <el-date-picker
                      v-model="orderInfo.expectedDeliveryTime"
                      type="date"
                      placeholder="请选择预期时间"
                      format="YYYY/MM/DD"
                  />
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">*负责人</div></td>
                <td class="el-table__cell is-leaf">
                  <el-input
                      style="width: 80%"
                      v-model="orderInfo.responsiblePerson"
                      placeholder="请选择负责人"
                      clearable
                  />
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">*联系电话</div></td>
                <td class="el-table__cell is-leaf">
                  <el-input
                      style="width: 88%"
                      v-model="orderInfo.contactPhone"
                      placeholder="请输入联系电话"
                      clearable
                  />
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">*收货地址</div></td>
                <td class="el-table__cell is-leaf" :colspan="2">
                  <el-input
                      v-model="orderInfo.deliveryAddress"
                      placeholder="请填写收货地址"
                      clearable
                  />
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card>
          <template #header><Goods style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">货品信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <el-table v-loading="loading" :data="showProductForm">
              <el-table-column label="货品编码" align="center" prop="rawProductCode" width="120"/>
              <el-table-column label="货品名称" align="center" prop="name" width="110"/>
              <el-table-column label="货品图片" align="center" prop="picture" width="120">
                <template #default="scope">
                  <image-preview :src="scope.row.picture" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column label="货品单价(元)" align="center" prop="unitPrice" width="100"/>
              <el-table-column label="货品描述" align="left" prop="description" width="240" header-align="center"/>
              <el-table-column label="待定数量" align="center" width="100">
                <template #default="scope">
                  <span>{{getDefaultNum(scope.row.name) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="订购数量" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.orderNum"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="View" @click="showDetail(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="display: flex;justify-content: center;margin-top: 10px">
              <el-button type="primary"
                         class="mb-4"
                         plain
                         icon="Plus"
                         @click="isVisible=true;"
              >添加备注</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24">
        <div style="display: flex; justify-content: right;
                margin-top: 30px; margin-right: 20px;gap: 10px">
          <el-button
              type="primary"
              round
              icon="Back"
              class="custom-large-button"
              @click="handleBack"
              style="background-color: #f44336"
          >退出</el-button>
          <el-button
              type="primary"
              round
              icon="Pointer"
              class="custom-large-button"
              @click="handleOrderGenerate"
          >提交</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 货品详情 -->
    <el-dialog title="货品详情" v-model="open" width="800px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="货品编码：">{{form.rawProductCode}}</el-form-item>
            <el-form-item label="供货商名称：">{{form.companyName}}</el-form-item>
            <el-form-item label="保质期：">{{form.shelfLife}} (天)</el-form-item>
            <el-form-item label="原产地：">{{form.origin}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称：">{{form.name}}</el-form-item>
            <el-form-item label="货品种类：">{{form.goodsCategory}}</el-form-item>
            <el-form-item label="温度要求：">{{form.storageTemperature}}</el-form-item>
            <el-form-item label="库存量：">{{form.stockQuantity}} ({{form.stockUnit}})</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品图片：" showTip="false">
              <el-image :src="form.picture" style="width: 150px; height: 150px;" fit="cover"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品描述：">{{form.description}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品规格：">{{form.specification}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格信息：">{{form.priceInformation}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">{{form.remarks}}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加备注 -->
    <el-dialog title="添加备注" v-model="isVisible" width="800px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="备注">
          <el-input type="textarea" v-model="orderInfo.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isVisible = false">确 定</el-button>
          <el-button @click="cancelRemarks">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DetailOrder">

import {useRouter} from "vue-router";
import {getProducts, generateOrderNumber, updateOrdergenerate} from "@/api/settled/ordergenerate";
//import { addOrdermaintain } from "@/api/ordermaintain/ordermaintain.js"
import { getPurchaseplanList } from "@/api/purchaseplan/purchaseplan.js"
import useDictStore from '@/store/modules/dict'
//import {addDetailorder} from "@/api/detailorder/detailorder.js";

const { proxy } = getCurrentInstance();

const router = useRouter();
const selectedProducts = ref([]); // 记录选择的货品
const productsNum = ref(0); // 记录选择货品的种类数
const suppliers =ref([]); // 记录所有的供货商
const rawProductForm = ref([]); // 记录所有的货品信息
const showProductForm = ref([]); // 展示特定供货商的货品
const loading = ref(false); // 展示图片是否正在加载
const open = ref(false); // 控制详情展示对话框显示
const isVisible = ref(false); // 填写备注
const form = ref({}); // 详情展示
const planNoList = ref([]) // 选中计划
const planInfo = ref({})
const orderDetails = ref([])
const orderInfo = ref({
  orderNo: '',
  orderTime: '',
  companyName: '',
  deliveryAddress: null,
  expectedDeliveryTime: null,
  totalAmount: 0.0,
  currencyUnit: '元',
  contactPhone: null,
  responsiblePerson: null,
  remarks: ''
});

/** 初始化 **/
function initial() {
  //初始化供货商
  let products = useDictStore().getDict("products");
  selectedProducts.value = products;
  productsNum.value = products.length;
  suppliers.value = useDictStore().getDict("suppliers")
  planNoList.value = useDictStore().getDict("planNoList")
  orderInfo.value.orderTime = getFormattedTime();
  orderInfo.value.companyName = suppliers.value[0];

  // 删除键值
  useDictStore().removeDict("products");
  useDictStore().removeDict("suppliers");
  useDictStore().removeDict("planNoList");

  //初始化货品信息
  loading.value = true
  getProducts(selectedProducts.value).then(response => {
    rawProductForm.value = response.data;
    showProductForm.value = rawProductForm.value.filter(
        item => item.companyName == orderInfo.value.companyName);
    loading.value = false;
  });

  //初始化计划信息
  getPurchaseplanList(planNoList.value).then(response => {
    planInfo.value = response.data;
  })

  //初始化订单编号
  orderInfo.value.orderNo = generateOrderNumber();
}

/** 获取当前时间 **/
function getFormattedTime(){
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/** 获取默认购买数量 **/
function getDefaultNum(name) {
  for(let i = 0; i < productsNum.value; i++) {
    let item = planInfo.value[i];
    if(item.rawProductName === name) {
      return item.quantity -item.purchaseQuantity > 0 ?
          item.quantity -item.purchaseQuantity : 0;
    }
  }
}

/** 选择框选中的供货商变化 **/
function handleSupplierChange(supplier) {
  loading.value = true;
  showProductForm.value = rawProductForm.value.filter(
      item => item.companyName === supplier);
  loading.value = false;
}

/** 展示货品详情 **/
function showDetail(row) {
  open.value = true;
  form.value = row;
}

/** 生成订单 **/
function handleOrderGenerate() {
  if(!checkOrder()){
    return;
  }
  //添加订单
  //addOrdermaintain(orderInfo.value).then(response => {
  //  proxy.$modal.msgSuccess("新增成功");
  //});
  //设置订单详情
  //setDetailOrder();
  //for(let i = 0; i < productsNum.value; i++) {
  //  addDetailorder(orderDetails.value[i]);
  //}
  //修改采购计划
  setOrderAmount();
  for(let i = 0; i < productsNum.value; i++) {
    updateOrdergenerate(planInfo.value[i]);
  }
  handleBack();
}

/** 提交订单判断 **/
function checkOrder(){
  if(orderInfo.value.companyName === ""||
      orderInfo.value.companyName == null){
    proxy.$modal.msgWarning("供货商不能为空");
    return false;
  }
  else if(orderInfo.value.contactPhone === ""||
      orderInfo.value.contactPhone == null){
    proxy.$modal.msgWarning("联系电话不能为空");
    return false;
  }
  else if(orderInfo.value.deliveryAddress === ""||
      orderInfo.value.deliveryAddress == null){
    proxy.$modal.msgWarning("收货地址不能为空");
    return false;
  }
  else if(orderInfo.value.responsiblePerson === ""||
      orderInfo.value.responsiblePerson == null){
    proxy.$modal.msgWarning("负责人不能为空");
    return false;
  }
  return true;
}

/** 获取每个货品的订购数量 **/
function setOrderAmount(){
  for(let i = 0; i < productsNum.value; i++) {
    let orderAmount = showProductForm.value[i].orderNum;
    let rawProductName = showProductForm.value[i].name;
    for(let j = 0; j < productsNum.value; j++) {
      if(planInfo.value[j].rawProductName === rawProductName){
        planInfo.value[j].purchaseQuantity += orderAmount;
        planInfo.value[j].planStatus = '已执行';
        if(planInfo.value[j].purchaseQuantity >= planInfo.value[j].quantity){
          planInfo.value[j].purchaseStatus = '已完成';
        }
        break;
      }
    }
  }
}

/** 设置订单详情 **/
function setDetailOrder(){
  orderDetails.value = showProductForm.value;
  let orderNo = orderInfo.value.orderNo;
  for(let i = 0; i < productsNum.value; i++) {
    orderDetails.value[i].orderNo = orderNo;
    orderDetails.value[i].quantity = showProductForm.value[i].orderNum;
  }
}

/** 退出 **/
function handleBack(){
  proxy.$tab.closeOpenPage(router.currentRoute.value);
  proxy.$router.push({
    path:'/order/ordergenerate',
  });
}

/** 取消备注 **/
function cancelRemarks(){
  isVisible.value = false;
  orderInfo.value.remarks = '';
}

initial()
</script>

<style scoped lang="scss">
.custom-large-button {
  font-size: 17px; /* 调整字体大小 */
  padding: 15px 30px; /* 增加内边距 */
  height: 40px; /* 设置高度 */
  width: 90px; /* 设置宽度 */
}
</style>